package com.atguigu.tingshu.album.service.impl;

import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.album.service.FileUploadService;
import io.minio.*;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.util.UUID;

/**
 * ClassName: FileUploadServiceImpl
 * Package: com.atguigu.tingshu.album.service.impl
 * Description: 文件上传服务
 */
@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinioConstantProperties minioConstantProperties;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @Override
    @SneakyThrows
    public String upload(MultipartFile file) {
        //判断桶是否存在
        if(!minioClient.bucketExists(
                BucketExistsArgs.builder().bucket(minioConstantProperties.getBucketName()).build())){
            //桶不存在则创建
            minioClient.makeBucket(MakeBucketArgs.builder()
                            .bucket(minioConstantProperties.getBucketName()).build());
        }

        //上传文件
        //创建文件名
        String fileName = UUID.randomUUID().toString().replaceAll("-", "");
        minioClient.putObject(PutObjectArgs.builder()
                        //设置文件类型
                        .contentType(file.getContentType())
                        //上传到哪个桶
                        .bucket(minioConstantProperties.getBucketName())
                        //文件名
                        .object(fileName)
                        //文件输入流
                        .stream(file.getInputStream(),file.getSize(),-1)
                .build());

        //返回rul
        return minioConstantProperties.getEndpointUrl() + "/" + minioConstantProperties.getBucketName() + "/" + fileName;

    }

}
